/**
 * @this
 *
 * @flow
 */

import React, { Component } from 'react'
import {
  StyleSheet,
  View,
  Text,
  Button,
  Keyboard,
  TextInput,
} from 'react-native'

import store from 'react-native-simple-store'
import RXEmitter from 'react-native-rxemitter'

const DEFAULT_TITLE = '编辑域名地址'
export default class SwithDns extends Component {
  static navigationOptions = ({ navigation, route }) => ({
    headerTitle: route.params.title || DEFAULT_TITLE,
    headerRight: () => (
      <Button
        title={'保存'}
        onPress={e => {
          RXEmitter.emit('edit2_save')
        }}
      />
    ),
  })

  constructor(props) {
    super(props)
    const navParams = this.props.route.params || {}
    const url = navParams.url || ''
    this.defaultUrl = url

    this.state = {
      url,
    }
  }

  componentDidMount() {
    RXEmitter.addListener(this, 'edit2_save', this._save)
  }

  componentWillUnmount() {
    RXEmitter.removeLister(this, 'edit2_save')
  }

  setDiyUrl(diyUrl = '') {
    store.save('diyUrl', diyUrl || '')
  }

  _save = () => {
    const nav = this.props.navigation || {}
    const route = this.props.route || {}
    const { url } = this.state

    Keyboard.dismiss()

    if (!url) {
      alert('地址为空')
      return
    }

    if (this.defaultUrl === url) {
      nav.goBack()
      return
    }

    this.setDiyUrl(url)
    const navParams = route.params || {}
    const nullfunc = () => {}
    const callback = navParams.callback || nullfunc
    callback && callback()
    nav.goBack()
  }

  formatSpace = (string) => {
    if (!string) return ''
    return string.replace(/\s+/g, '')
  }

  render() {
    const { url } = this.state

    return (
      <View style={styles.container}>
        <Text style={{ marginLeft: 10 }}>{this.defaultUrl}</Text>
        <View style={styles.textInputView}>
          <TextInput
            style={styles.textInput}
            value={url}
            multiline={true}
            onChangeText={(value) => {
              this.setState({ url: this.formatSpace(value) })
            }}
          />
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 30,
    backgroundColor: 'white',
  },
  textInputView: {
    marginTop: 5,
    borderWidth: 1,
    padding: 5,
    paddingHorizontal: 10,
    borderColor: '#D3D3D3'
  },
  textInput: {
    padding: 0,
  },
})